import React from 'react'
import { Tree, Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, Radio, Modal, Message } from 'antd';
import api from '../../../api/role';
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const TreeNode = Tree.TreeNode;


import PanelBox from '../../../components/PanelBox';
import Antdicons from '../Antdicon';

import './index.less'

class RegistrationForm extends React.Component {
  state = {
    sumitLoad: false
  };

  submit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (values.menus) {
        values.menus = values.menus.concat(this.state.halfCheckedKeys || []);
      }
      if (!err) {
        if (values.id) {
          this.edit(values);
        } else {
          this.create(values);
        }

      }
    });
  }

  edit = (values) => {
    this.setState({
      sumitLoad: true
    });
    api.put('/edit', { ...values }).then((res) => {
      const result = res.data;
      if (result.code == 0) {
        Message.success('修改成功！');
        this.props.ok();
      } else {
        Message.error(result.message);
      }
      this.setState({
        sumitLoad: false
      });
    });
  }

  create = (values) => {
    this.setState({
      sumitLoad: true
    });
    api.post('/create', { ...values }).then((res) => {
      const result = res.data;
      if (result.code == 0) {
        Message.success('添加成功！');
        this.props.ok();
      } else {
        Message.error(result.message);
      }
      this.setState({
        sumitLoad: false
      });
    });
  }

  find = () => { }

  close = () => {
    this.props.close();
  }

  componentDidMount = () => {
    this.setState({
      loading: true
    });

  }

  onExpand = (expandedKeys) => {
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  }
  onCheck = (checkedKeys, e) => {
    this.setState({
      checkedKeys: checkedKeys,
      halfCheckedKeys: e.halfCheckedKeys
    });
  }
  onSelect = (selectedKeys, info) => {
  }
  checkedKeys = () => {
    this.setState({
      checkedKeys: this.props.checkedTree
    })
    return this.state.checkedKeys;
  }
  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} />;
    });
  }
  componentWillReceiveProps(nextProps) {
    if (this.props.clearForm != nextProps.clearForm && nextProps.clearForm == false) {
      this.setState({
        checkedKeys: [],
        expandedKeys: []
      })
      this.props.form.resetFields();
    }
    if (this.props.loadCheckedKeys != nextProps.loadCheckedKeys && nextProps.loadCheckedKeys == true) {
      this.props.form.setFieldsValue({ "menus": nextProps.loadCheckedAllKeys })
      this.setState({
        halfCheckedKeys: [],
        checkedKeys: nextProps.checkedKeys
      });
    }
  }

  render() {
    const { getFieldDecorator, resetFields } = this.props.form;
    const record = this.props.record;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };

    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 14,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };

    return (
      <div>
        <Form onSubmit={this.submit}>
          {getFieldDecorator('id', {
            initialValue: record ? record.id : null
          })(
            <Input type="hidden" />
            )}

          {getFieldDecorator('parentIds', {
            initialValue: record ? record.parentIds : '0,'
          })(
            <Input type="hidden" />
            )}

          {getFieldDecorator('parentId', {
            initialValue: record ? record.parentId : '0'
          })(
            <Input type="hidden" />
            )}

          <FormItem
            {...formItemLayout}
            label="上级角色"
          >
            {getFieldDecorator('parentName', {
              initialValue: record ? record.parentName : '无',
            })(
              <Input disabled />
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="名称"
            hasFeedback
          >
            {getFieldDecorator('name', {
              rules: [{ required: true, message: '名称不能为空!' }],
              initialValue: record ? record.name : ''
            })(
              <Input />
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="英文名称"
            hasFeedback
          >
            {getFieldDecorator('enname', {
              rules: [{ required: true, message: '英文名称不能为空!' }],
              initialValue: record ? record.enname : ''
            })(
              <Input />
              )}
          </FormItem>

          <FormItem
            {...formItemLayout}
            label="状态"
            extra="该菜单或操作是否显示到系统菜单中"
          >
            {
              getFieldDecorator('useable', {
                initialValue: record ? (record.useable || "1") : '0'
              })(
                <RadioGroup>
                  <Radio value="1" >正常</Radio>
                  <Radio value="0">禁用</Radio>
                </RadioGroup>
                )
            }
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="角色菜单"
          >
            {getFieldDecorator('menus', {
              rules: [{ required: true, message: '菜单不能为空!' }],
              trigger: "onCheck"
            })(
              <Tree
                checkable
                onExpand={this.onExpand}
                expandedKeys={this.state.expandedKeys}
                autoExpandParent={this.state.autoExpandParent}
                onCheck={this.onCheck}
                checkedKeys={this.state.checkedKeys}
                propCheckedKey={this.props.checkedKeys}
                onSelect={this.onSelect}
                selectedKeys={this.state.selectedKeys}
              >
                {this.renderTreeNodes(this.props.menuTree)}
              </Tree>
              )}
            {}
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button loading={this.state.sumitLoad} type="primary" htmlType="submit" size="large" style={{ marginRight: '10px' }}>提交</Button>
            <Button onClick={this.close}>取消</Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}


class RoleManageRoleForm extends React.Component {
  state = {
    sumitLoad: false
  };

  submit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (values.roles) {
        values.roles = values.roles.concat(this.state.halfCheckedKeys || []);
      }
      values.roleId = values.id;
      if (!err) {
        this.requset(values);
      }

    });
  }

  requset = (values) => {
    this.setState({
      sumitLoad: true
    });
    api.post('/roleManage', { ...values }).then((res) => {
      const result = res.data;
      if (result.code == 0) {
        Message.success('保存分配角色成功！');
        this.props.ok();
      } else {
        Message.error(result.message);
      }
      this.setState({
        sumitLoad: false
      });
    });
  }

  close = () => {
    this.props.close();
  }

  componentDidMount = () => {
    this.setState({
      loading: true
    });

  }

  onExpand = (expandedKeys) => {
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  }
  onCheck = (checkedKeys, e) => {
    this.setState({
      checkedKeys: checkedKeys,
      halfCheckedKeys: e.halfCheckedKeys
    });
  }
  onSelect = (selectedKeys, info) => {
  }
  checkedKeys = () => {
    this.setState({
      checkedKeys: this.props.checkedTree
    })
    return this.state.checkedKeys;
  }
  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} />;
    });
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.clearForm != nextProps.clearForm && nextProps.clearForm == false) {
      this.setState({
        checkedKeys: [],
        expandedKeys: []
      })
      this.props.form.resetFields();
    }
    if (this.props.loadCheckedKeys != nextProps.loadCheckedKeys && nextProps.loadCheckedKeys == true) {
      this.props.form.setFieldsValue({ "roles": nextProps.loadCheckedAllKeys })
      this.setState({
        halfCheckedKeys: [],
        checkedKeys: nextProps.checkedKeys
      });
    }
  }

  render() {
    const { getFieldDecorator, resetFields } = this.props.form;
    const record = this.props.record;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };

    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 14,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };

    return (
      <div>
        <Form onSubmit={this.submit}>
          {getFieldDecorator('id', {
            initialValue: record ? record.id : null
          })(
            <Input type="hidden" />
            )}

          <FormItem
            {...formItemLayout}
            label="分配角色"
          >
            {getFieldDecorator('name', {
              initialValue: record ? record.name : '',
            })(
              <Input disabled />
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="被分配角色"
          >
            {getFieldDecorator('roles', {
              trigger: "onCheck"
            })(
              <Tree
                checkable
                onExpand={this.onExpand}
                expandedKeys={this.state.expandedKeys}
                autoExpandParent={this.state.autoExpandParent}
                onCheck={this.onCheck}
                checkedKeys={this.state.checkedKeys}
                propCheckedKey={this.props.checkedKeys}
                onSelect={this.onSelect}
                selectedKeys={this.state.selectedKeys}
              >
                {this.renderTreeNodes(this.props.roleTree)}
              </Tree>
              )}
            {}
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button loading={this.state.sumitLoad} type="primary" htmlType="submit" size="large" style={{ marginRight: '10px' }}>提交</Button>
            <Button onClick={this.close}>取消</Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

export const ManageRoleForm = Form.create()(RoleManageRoleForm);
export const WrappedRegistrationForm = Form.create()(RegistrationForm);
